var _ = require('lodash');
var axios = require('axios');
import { Toast } from 'vant';
import { setSession,getSession } from "./session.js";

const ajaxRequest = function (reqUrl,reqData={},showError=true) {
    let $this = this;
    let contextPath = process.env.VUE_APP_APIURL;
    //兼容问题
    if(_.isEmpty(Promise.prototype.finally)) {
        Promise.prototype.finally = function (callback) {
            var Promise = this.constructor;
            return this.then(
                function (value) {
                    Promise.resolve(callback()).then(
                        function () {
                            return value;
                        }
                    );
                },
                function (reason) {
                    Promise.resolve(callback()).then(
                        function () {
                            throw reason;
                        }
                    );
                }
            );
        }
    }

    return new Promise(function(resolve, reject){
        //请求头部
        let headers = {};
        headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";

        let accessToken = getSession("x-auth-token");
        if(!_.isEmpty(accessToken) && accessToken !== 'null'){
            headers["x-auth-token"] = accessToken;
        }

        //请求参数
        var params = new URLSearchParams();
        if(_.isObject(reqData)){
            _.forEach(reqData,function (val,key) {
                params.append(key,val);
            });
        }

        if('http:' == document.location.protocol){
            contextPath = contextPath.replace(/^https/,"http");
        }

        axios({
            method: 'post',
            url: contextPath + reqUrl,
            data:params,
            headers:headers
        }).then(function (response) {
            if(!_.isEmpty(response.headers["x-auth-token"])){
                setSession("x-auth-token",response.headers["x-auth-token"]);
            }
            resolve(response.data);
        }).catch(function (error) {
            if(showError){
                let status = 200;
                let showMsg = "";
                if (error.response) {
                    status = error.response.status;
                } else if (error.request) {
                    status = 502;
                } else {
                    status = 501;
                }

                if(401 == status){
                    showMsg = "未登陆";
                } else if(403 == status){
                    showMsg = "您没有访问权限";
                } else if(404 == status){
                    showMsg = "请求不存在";
                } else if(400 == status){
                    showMsg = "服务器无法解析参数";
                } else if(500 == status){
                    showMsg = "服务器异常";
                } else if(502 == status){
                    showMsg = "服务不可用";
                } else{
                    showMsg = "无效的请求";
                }
                if(401 !== status) {
                    Toast({message: reqUrl + showMsg, position: 'top'});
                }else{
                    let model = process.env.VUE_APP_MODEL;
                    if(model !== 'mock') {
                        setSession("x-auth-token","null");

                        $this.$router.push({path: "/login?toPage=" + $this.$route.fullPath});
                    }
                }
            }else{
                reject({
                    response:error
                });
            }
        });
    });
};

export default ajaxRequest;